<template>
    <div class="mx-auto px-4 py-8">
      <!-- 题型导航 -->
      <div class="mb-6 flex items-center space-x-4 bg-white p-6 rounded-lg ">
        <button class="text-sm text-gray-400">题型</button>
        <button v-for="(question, index) in questionTypeList" 
                :key="index"
                :class="[
                  'px-4 py-2 rounded-full text-sm whitespace-nowrap !rounded-button border border-gray-200 transition duration-300 ease-in-out focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent',
                 currentType === index ? 'bg-blue-500 text-white' : 'bg-white text-gray-600  hover:bg-sky-100 hover:text-blue-400 hover:border-sky-200'
                ]"
                @click="setCurrentType(index)">
          {{ question }}
        </button>
      </div>

      <!-- 主要编辑区域 -->
      <div class="bg-white rounded-xl p-6 shadow-sm">
        <div class="text-gray-500 mb-6">{{ questionTypeList[currentType] }}</div>
        <div class="mb-6">
          <!-- 富文本工具栏 题干 -->
           <div  class="h-300 mb-6 ">
           <RichTextEditor :html="questionForm.questionContent" @change="getHtml" />
           </div>
          <!--选择题选项列表 -->
          <div v-if="questionForm.questionType==='单选题'||questionForm.questionType==='多选题'">
            <div class="space-y-4">
              <div v-for="(option, index) in questionForm.options" :key="index" class="flex  space-x-4" @mouseenter="option.isClose=true"  @mouseleave="option.isClose=false">
                <el-tooltip
                  effect="dark"
                  content="设为答案"
                  placement="top">
                <span :class="['text-gray-500 w-8 h-8  leading-8 text-center border rounded-full',option.isAnswer?'bg-blue-500 text-white':'' ]"
                  @click="choiceAnswer(index)">{{ String.fromCharCode(65 + index) }}</span>
              </el-tooltip>
                <div  class="border border-gray-200  rounded-lg p-2 w-full" v-show="!option.isEditing" 
                  @click="handleClickOption(index)" >
                  <span  v-show='option.content.trim()=="" || option.content=="<p><br></p>"' class="text-gray-400">请输入选项{{String.fromCharCode(65 + index)}}内容</span>
                  <span v-html="option.content" ></span>
                </div>
                  <div class="flex-1" v-show="option.isEditing" >
                    <RichTextEditor :html="option.content" @change="(html)=>{option.content = html}" />
                  </div>
                <div class="w-8">
                  <el-button v-if="option.isClose" class="font-bold text-xl" type="info" icon="Close" link @click="removeOption(index)"  />
                </div>
              </div>
            </div>

            <!-- 添加选项按钮 -->
            <el-button 
              type="primary" 
              plain
              class="mt-4 !rounded-button"
              @click="addOption">
              <el-icon class="mr-2"><Plus /></el-icon>
              添加选项
            </el-button>
          </div>
          <!-- 填空题 -->
          <div v-else-if="questionForm.questionType==='填空题'">
            <div class="space-y-4">
              <div v-for="(option, index) in questionForm.gapOptions" :key="index" class="flex  space-x-6" @mouseenter="option.isClose=true"  @mouseleave="option.isClose=false">
                <span :class="['text-gray-500 w-8 h-8 leading-8 text-center  whitespace-nowrap' ]">第{{ index+1 }}空</span>
              
                <div  class="border border-gray-200  rounded-lg p-2 w-full" v-show="!option.isEditing" 
                  @click="handleClickOption(index)" >
                  <span  v-show='option.content.trim()===""' class="text-gray-400">请输入答案</span>
                  <span v-html="option.content"></span>
                </div>
                
                  <div class="flex-1" v-show="option.isEditing" >
                    <RichTextEditor :html="option.content" @change="(html)=>{option.content = html}" />
                  </div>
                <div class="w-8">
                  <el-button v-if="option.isClose" class="font-bold text-xl" type="info" icon="Close" link @click="removeGapOption(index)"  />
                </div>
              </div>
            </div>

            <!-- 添加选项按钮 -->
            <el-button 
              type="primary" 
              plain
              class="mt-4 !rounded-button"
              @click="addGapOption">
              <el-icon class="mr-2"><Plus /></el-icon>
              添加选项
            </el-button>

          </div>
          <!-- 判断题 -->
          <div v-else-if="questionForm.questionType==='判断题'">
             <div class="space-y-4">
               <div v-for="(option, index) in judgeOptions" :key="index" class="flex  space-x-4">
                  <el-tooltip
                  effect="dark"
                  content="设为答案"
                  placement="top">
                <span :class="['text-gray-500 w-8 h-8  leading-8 text-center border rounded-full',option.isAnswer?'bg-blue-500 text-white':'' ]"
                  @click="choiceAnswer(index)">{{ String.fromCharCode(65 + index) }}</span>
              </el-tooltip>
                <span>{{ option.content }}</span>
              </div>

             </div>
            
          </div>
          <!-- 简答题其他都通简答题的模版 -->
          <div v-else>
               <div  class="border border-gray-200  rounded-lg p-2 w-full"  @click="handleEssay"  v-show="!isShowEssayEditor">
              <span v-show='questionForm.essayAnswer==""' class="text-gray-400">请输入答案</span>
              <span v-html="questionForm.essayAnswer"></span>
             </div>
             <RichTextEditor v-show="isShowEssayEditor" :html="questionForm.essayAnswer" @change="html=>questionForm.essayAnswer=html"/>

          </div>

        </div>

        <!-- 答案解析 -->
        <div class="mb-6">
          <!-- <div class="text-gray-600 mb-2">答案解析</div> -->
             <div  class="border border-gray-200  rounded-lg p-2 w-full" v-show="!questionForm.analysis.isEditing" @click="handleClickAnalysis">
              <span v-show='questionForm.analysis.content==""' class="text-gray-400">请输入答案解析</span>
              <span v-html="questionForm.analysis.content"></span>
             </div>
          <!-- <el-input
            v-show="!questionForm.analysis.isEditing"
            type="textarea"
            v-model="questionForm.analysis.content"
            :rows="2"
            placeholder="请输入答案解析"
            @focus="handleClickAnalysis"
          /> -->
         <RichTextEditor :html="questionForm.analysis.content" @change="(html)=>{questionForm.analysis.content = html}"  v-show="questionForm.analysis.isEditing"/>
        </div>

        <!-- 难度设置 -->
        <div class="mb-6 flex items-center gap-4">
          <div class="text-gray-600 mb-2 w-20 ">难度</div>
          <el-select v-model="questionForm.difficulty" placeholder="请选择难度" class="w-40">
            <el-option
              v-for="item in difficulties"
              :key="item.value"
              :label="`(${item.value}) ${item.label}`"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 知识点 -->
        <div class="mb-6 flex items-center ">
          <div class="text-gray-600 mb-2  w-20">知识点</div>
          <div class="ml-4 flex flex-wrap items-center">
            <el-tag
                v-for="tag in questionForm.knowledgePoints"
                :key="tag"
                class="mr-2"
                size="large"
                closable
                @close="removeKnowledgePoint(tag)"
            >
                {{ tag }}
            </el-tag>
            <el-button 
                class="!rounded-button" 
                @click="showAddKnowledgePoint = true">
                <el-icon><Plus /></el-icon>
                添加知识点
            </el-button>
          </div>
        </div>
        <!-- 标签 -->
        <div class="mb-6 flex items-center ">
          <div class="text-gray-600 mb-2 w-20 ">标签</div>
          <div class="ml-4 flex flex-wrap items-center">
            <el-tag
                v-for="tag in questionForm.tags"
                :key="tag"
                size="large"
                class="mr-2"
                closable
                @close="removeTag(tag)"
            >
                {{ tag }}
            </el-tag>
            
            <el-button 
                class="!rounded-button" 
                @click="showTagsDialog = true">
                <el-icon><Plus /></el-icon>
                关联标签
            </el-button>
          </div>
        </div>

         <!-- 提交按钮 -->
      <div class="mt-6 py-4 flex items-center justify-center bg-white">
        <el-button type="success" @click="saveQuestion">保存</el-button>
        <el-button type="primary" @click="EditNextQuestion">继续出题</el-button>
      </div>
      </div>
      <KnowledgeAndTagDialog  v-model:showAddKnowledgePoint="showAddKnowledgePoint" v-model:showTagsDialog="showTagsDialog" 
      @sendKnowledgeData="addKnowledgeToQuestion" @sendTagData="addTagsToQuestion" />

    </div>
</template>

<script  setup>
import { ref,watch,nextTick, reactive,onMounted} from 'vue';
import 'katex/dist/katex.min.css'
import katex from 'katex'
import { Plus } from '@element-plus/icons-vue';
import { useRouter,useRoute } from 'vue-router';
import RichTextEditor from '@/components/RichTextEditor.vue';
import KnowledgeAndTagDialog from '@/views/exam/KnowledgeAndTagDialog.vue';
const router = useRouter();
const  route = useRoute();//判断是否传递参数id
onMounted(()=>{
  if(route.query.id){//如果有传递参数id，则加载题目详情
    const id = route.query.id;
    console.log("id:",id)
    // getQuestionDetailById(id);
  }
})

const currentType = ref(0);
const questionTypeList=ref(['单选题' ,'多选题', '填空题','判断题','简答题' , '更多' ])
//定义整个表单数据 
const questionForm = reactive({
  id: null,
  questionType:'单选题',//当前题型
  questionContent: '',//问题内容
  options: [//选项
    { content: '',isEditing: false,isClose:false,isAnswer:false },
    { content: '',isEditing: false,isClose:false,isAnswer:false},
    { content: '',isEditing: false,isClose:false,isAnswer:false},
    { content: '',isEditing: false,isClose:false,isAnswer:false }
  ],
  gapOptions:[
    { content: '',isEditing: false,isClose:false,isAnswer:false },
  ],//填空题每个空答案
  answer: [], //选择题答案
  essayAnswer:'',//简答题答案
  analysis:{content:'',isEditing:false},//答案解析
  difficulty: '0.8',//难度
  knowledgePoints: [],//知识点
  tags: [],//标签 
})
//判断题选项
const judgeOptions = ref([
  { content: '正确', value: true ,isAnswer:true},
  { content: '错误', value: false,isAnswer:false }
]);

const showAddKnowledgePoint = ref(false);
// 关联标签
const  showTagsDialog = ref(false);

const difficulties = [
  { value: '0.1', label: '难' },
  { value: '0.2', label: '难' },
  { value: '0.3', label: '中' },
  { value: '0.4', label: '中' },
  { value: '0.5', label: '中' },
  { value: '0.6', label: '中' },
  { value: '0.7', label: '中' },
  { value: '0.8', label: '易' },
  { value: '0.9', label: '易' },
  { value: '1.0', label: '易' },
];
// 当选项内容变化时，重新渲染公式
watch(()=>questionForm.options,(newVal)=>{
   nextTick(() => {
    // 匹配富文本编辑器生成的公式span元素
    document.querySelectorAll('span[data-w-e-type="formula"]').forEach(span => {
      const latex = span.getAttribute('data-value')
      if (latex) {
        // 清空span内容并渲染公式
        span.innerHTML = ''
        katex.render(latex, span, {
          displayMode: false, // 内联公式
          throwOnError: false,
          trust: (context) => ['\\htmlId', '\\href'].includes(context.command)
        })
      }
    })
  })

},{deep:true})



// 富文本编辑器内容变化事件
const getHtml = (html) => {
  questionForm.questionContent = html;
};

// 当前题型的选择事件
const setCurrentType = (index) => {
  // 设置当前题目类型索引和题目类型值
  currentType.value = index;
  questionForm.questionType = questionTypeList.value[index];
  console.log(questionForm.questionType,'iiiii');

   //切换题目类型的时候 清空所有数据
  questionForm.questionContent = '';//问题内容
  questionForm.options = [
    { content: '',isEditing: false,isClose:false,isAnswer:false },
    { content: '',isEditing: false,isClose:false,isAnswer:false},
    { content: '',isEditing: false,isClose:false,isAnswer:false},
    { content: '',isEditing: false,isClose:false,isAnswer:false }
  ];//选项
  questionForm.gapOptions=[
    { content: '',isEditing: false,isClose:false,isAnswer:false },
  ];//填空题每个空答案
  questionForm.answer = []; //选择题答案
  questionForm.essayAnswer='';//简答题答案
  questionForm.analysis={content:'',isEditing:false};//答案解析
  questionForm.difficulty= '0.8';//难度
  questionForm.knowledgePoints = [];//知识点
  questionForm.tags = [];//标签 
};

/**
* 添加选项
* 如果选项数组的长度小于26，则向选项数组中添加一个新的空选项对象。
*/
const addOption = () => {
  if(questionForm.options.length < 26) {
    questionForm.options.push({ content: '' });
  }
};
/**
* 删除选项
* 如果选项数组的长度大于1，则从选项数组中删除最后一个选项对象。
*/
const removeOption = (index) => {
  if(questionForm.options.length > 1) {
    questionForm.options.splice(index, 1);
  }
}
// 添加填空题的答案 
const  addGapOption = () => {
  questionForm.gapOptions.push({ content: '' });
}
//删除填空题的answer
const  removeGapOption = (index) => {
  if(questionForm.gapOptions.length > 1) {
    questionForm.gapOptions.splice(index, 1);
  }
}

// 点击了某个选项的显示富文本
const  handleClickOption = (index) => {
  if(currentType.value === 0|| currentType.value === 1) {//如果单选或者多选
      questionForm.analysis.isEditing = false;//关闭解析的富文本编辑器

      questionForm.options.forEach((item,i)=>{
        if(index === i) {
          item.isEditing = true;
        }else {
          item.isEditing = false;
        }
      })
  }else if(currentType.value === 2) {//如果是填空题
    questionForm.analysis.isEditing = false;
    questionForm.gapOptions.forEach((item,i)=>{
      if(index === i) {
        item.isEditing = true;
      }else {
        item.isEditing = false;
      }
    })

    }

};
// 某个或者某些选项设为答案
const choiceAnswer=(index) => {
  console.log(index,'index选择选项',currentType.value,'currentType');
  // 题目为单选的情况 
  if(currentType.value === 0) {//单选题
    console.log('单选',1111);
    questionForm.options.forEach((item,i)=>{
      item.isAnswer = false;
    })
    questionForm.options[index].isAnswer = true;
  }else if(currentType.value=== 1) { //题目为多选的情况
    questionForm.options[index].isAnswer = !questionForm.options[index].isAnswer;
  }else if(currentType.value === 3) { //题目为判断题的情况
    judgeOptions.value.forEach((item,i)=>{
      item.isAnswer = false;
    })
    judgeOptions.value[index].isAnswer = !judgeOptions.value[index].isAnswer;
  }

  
};
// 简答题答案编辑
const isShowEssayEditor = ref(false);
//点击输入简答题的答案
const  handleEssay=() => { 
  isShowEssayEditor.value = true;
  questionForm.analysis.isEditing = false;
  questionForm.options.forEach(item=>{
    item.isEditing = false;
  })
};

//点击编辑
 const  handleClickAnalysis = () => {
  
  questionForm.analysis.isEditing = true;
  questionForm.options.forEach(item=>{
    item.isEditing = false;
  })
  isShowEssayEditor.value = false;
};
// 删除知识点
const removeKnowledgePoint = (knowledgePoint) => {
  questionForm.knowledgePoints= questionForm.knowledgePoints.filter(t => t !== knowledgePoint);
};
// 删除标签
const removeTag = (tag) => {
  questionForm.tags = questionForm.tags.filter(t => t !== tag);
};


// 从知识带你的弹框中获取到选择的知识点
const addKnowledgeToQuestion=(knowledge) => { 
  console.log(knowledge,'knowledge');
  knowledge.forEach(item=>{
    if(!questionForm.knowledgePoints.includes(item.name)){
      questionForm.knowledgePoints.push(item.name)
    }
  })

};

//从标签的弹框中获取到选择的标签
const addTagsToQuestion = (tag) => {
  console.log(tag,'tag')
  tag.forEach(item=>{
    if(!questionForm.tags.includes(item.name)){
      questionForm.tags.push(item.name)
    }
  })
}


//保存题目
 const saveQuestion = () => {
  console.log('点击了保存题目的按钮》》',questionForm)
 }

 //继续出题
 const   EditNextQuestion = () => {
  console.log('点击了继续出题的按钮》》')
 }



</script>

<style scoped>
.el-input :deep(.el-input__wrapper) {
  box-shadow: none !important;
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
}

.el-textarea :deep(.el-textarea__inner) {
  box-shadow: none !important;
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
}

.el-select :deep(.el-input__wrapper) {
  box-shadow: none !important;
  border: 1px solid #e5e7eb;
  border-radius: 0.5rem;
}
</style>

